package com.shanpin.shebao.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.shanpin.shebao.admin.db.AppDbRepository;
import com.shanpin.shebao.dao.CouponChannelDao;
import com.shanpin.shebao.model.CouponChannel;
import com.shanpin.shebao.utility.MoreCriteria;
import com.shanpin.shebao.utility.PageModel;

@Repository
public class CouponChannelDaoImpl implements CouponChannelDao {
	
	@Autowired
	private AppDbRepository app;
	
	private int getTotalRecord(MoreCriteria c){
		
		Long count = 0L;

		String sql = "SELECT COUNT(1) FROM t_sb_coupon_channel coupon_channel";
		
		sql = sql + c.getSqlString();
		
		count = app.queryLong(sql, c.getValueList().toArray());
		
		return count.intValue();
		
	}
	
	@Override
	public int add(String name) {
		String sql = "INSERT INTO t_sb_coupon_channel(name) VALUES (?)";
		int id = app.insert(sql,"id", name);
		
		return id;
	}

	@Override
	public PageModel queryPageBy(int pageNo, int pageSize, MoreCriteria c) {
		int start = (pageNo-1)*pageSize;
		
		String sql = "SELECT coupon_channel.* FROM t_sb_coupon_channel coupon_channel";
		PageModel pm = new PageModel();
		
		sql = sql + c.getSqlString();
		sql = sql + " order by id desc";
		sql = pm.getMySQLPageSQL(sql, start, pageSize);
		
		List<CouponChannel> recordList = app.query(sql, CouponChannel.mapper, c.getValueList().toArray());
		
		pm.setPageNo(pageNo);
		pm.setPageSize(pageSize);
		pm.setRecordList(recordList);
		pm.setTotalRecord(getTotalRecord(c));
		return pm;
	}
	
	@Override
	public CouponChannel queryBy(String id) {
		String sql = "SELECT * FROM t_sb_coupon_channel coupon_channel";
		sql = sql + " where coupon_channel.id = ?";
		
		CouponChannel couponChannel = app.queryT(sql, CouponChannel.mapper, id);
		
		return couponChannel;
	}

	@Override
	public List<CouponChannel> queryBy(String... id) {
		StringBuilder sb = new StringBuilder();
		
		for(String i: id) {
			sb.append("?,");
		}
		
		String ids = sb.toString();
		ids = ids.length() > 1? ids.substring(0, ids.lastIndexOf(",")):ids;
		
		String sql = "SELECT * FROM t_sb_coupon_channel coupon_channel";
		sql = sql + " where coupon_channel.id in (" + ids +")";
		
		List<CouponChannel> couponChannelList = app.query(sql, CouponChannel.mapper, id);
		
		return couponChannelList;
	}
	
}
